<template>
  <div>
    <attach-detail :project-data="projectData" v-loading="loading"></attach-detail>
    <attach-upload
      :tags="uploadTags"
      :view-mode="viewMode"
      :batch-no="queryId"
      v-bind="$listeners"
      @after-data="handleAfterData"
    >
      <template slot="header">
        <h3 class="attach-title">附件资料</h3>
        <hr />
      </template>
      <template slot="contract">
        <attach-contract
          :related-id="queryId"
          :view-mode="viewMode"
          :tag="contractTag"
          @get-contract="handleGetContract"
          @after-data="handleAfterData"
          @type-change="handleContractTypeChange"
          @success="handleContractSuccess"
        ></attach-contract>
      </template>
      <div slot="corp">
        <span v-if="viewMode">
          {{ { 0: '否', 1: '是' }[isCorp] }}
        </span>
        <c-radio-group
          v-else
          @change="updateStatus()"
          :options="[
            { label: '是', value: '1' },
            { label: '否', value: '0' },
          ]"
          v-model="isCorp"
        ></c-radio-group>
      </div>
    </attach-upload>

    <!-- {{ this.projectData.datum_status }}
    {{ currentStatus }} -->
    <div
      class="text-center mt-5"
      v-if="+currentStatus === 1 && +this.projectData.datum_status === 0"
    >
      <el-button type="primary" class="btn-long" :loading="submitLoading" @click="handleUpdate">
        确认提交
      </el-button>
      <el-button class="btn-long" :loading="submitLoading" @click="handleClose">取消</el-button>
    </div>
  </div>
</template>

<script>
// import { enumPersonalTags, enumCompanyTags } from '@/bank/views/fast/attach'

import AttachDetail from '@/bank/views/business/limit/history/attach/AttachDetail'
import AttachUpload from '@/bank/components/attach/Upload'
import AttachContract from '@/bank/views/business/limit/new/attach/AttachContract'

const contractSlot = 'contract'
export const enumPersonalTags = [
  { tag: '委保合同', required: true, slot: 'contract' },
  { tag: '资信表或尽调报告', required: true },
  { tag: '委托担保函', required: true },
  { tag: '委托担保项目表', required: true },
  { tag: '借据', required: false },
  { tag: '借款合同', required: false },
  { tag: '身份证或户口本', required: false },
  { tag: '结婚证', required: false },
  { tag: '其他', required: false },
]
export const enumCompanyTags = [
  { tag: '委保合同', required: true, slot: 'contract' },
  { tag: '资信表或尽调报告', required: true },
  { tag: '个人责任承诺函', required: true },
  { tag: '委托担保函', required: true },
  { tag: '委托担保项目表', required: true },
  { tag: '借据', required: false },
  { tag: '借款合同', required: false },
  { tag: '营业执照', required: false },
  { tag: '法定代表人身份证或户口本', required: false },
  { tag: '实际控制人是否是法人', slot: 'corp' },
  { tag: '实际控制人身份证或户口本', required: false },
  { tag: '其他', required: false },
]

export const enumRenewalTags = [
  { tag: '委保合同', required: true, slot: 'contract' },
  { tag: '借款合同或借据', required: false },
]
export default {
  components: {
    AttachDetail,
    AttachUpload,
    AttachContract,
  },
  props: {
    queryId: String,
    updateAttachStatus: Boolean,
    viewMode: { type: Boolean, default: true },
  },
  data() {
    return {
      loading: false,
      projectData: {},
      isOnlineSign: 2,
      attachs: [],
      tableName: 'datum_one_county_industry',
      signStatus: 0,
      customerSignApproval: 0,
      isCorp: '1',
      currentStatus: 0,
      submitLoading: false,
    }
  },
  computed: {
    enumRenewalTagsShow() {
      return this.viewMode
        ? [...enumRenewalTags, { tag: '其他', required: false }]
        : enumRenewalTags
    },
    isCompany() {
      return +this.projectData.customer_type === 1
    },
    // 是否续贷
    isContinue() {
      return +(this.projectData.renewal_type || '') === 2
    },
    uploadTags() {
      return this.isContinue
        ? this.enumRenewalTagsShow
        : this.isCompany
        ? +this.isCorp === 0
          ? enumCompanyTags
          : enumCompanyTags.filter(item => item.tag !== '实际控制人身份证或户口本')
        : enumPersonalTags
    },
    relatedId() {
      return this.projectData.customer_related_id
    },
    contractTag() {
      const tag = this.uploadTags.find(it => it.slot === contractSlot) || {}
      return {
        tag: tag.tag,
        required: tag.required,
      }
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    handleClose() {
      this.$emit('close')
    },
    getData() {
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, { 'customer_related_id.eq': this.queryId })
        .then(res => {
          this.projectData = res?.data?.[0] ?? {}
          this.isCorp = this.projectData.is_corp_con || '1'
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleAfterData({ list, emit }) {
      if (!this.updateAttachStatus) return
      this.attachs = list
      const listObj = this.attachs.reduce((prev, curr) => {
        const tag = curr.attachment_type
        if (!prev[tag]) prev[tag] = []
        prev[tag].push(curr)
        return prev
      }, {})
      const isAllUpload = this.uploadTags.every(tag => {
        const isOnline = tag.slot === contractSlot && this.isOnlineSign === 1
        if (isOnline) {
          return this.customerSignApproval === 1
        }
        if (!tag.required) return true
        const atts = listObj[tag.tag]
        return atts && atts.length > 0
      })
      this.currentStatus = isAllUpload ? 1 : 0
      if (emit) {
        this.updateStatus()
      }
    },

    // 委托合同附件
    handleGetContract({ contract }) {
      this.isOnlineSign = +(contract.is_online_sign || 0)
      this.signStatus = +(contract.sign_status || 0)
      this.customerSignApproval = +(contract.customer_sign_approval || 0)
    },
    handleContractTypeChange(type) {
      this.isOnlineSign = type
      this.$emit('after-data', {})
      this.updateStatus()
    },
    handleContractSuccess() {
      this.signStatus = 1
      this.updateStatus()
    },

    handleUpdate() {
      this.submitLoading = true
      // 更新状态
      this.$api
        .updateData({
          table: 'datum_one_county_industry',
          id: this.relatedId,
          data: {
            datum_status: 1,
          },
        })
        .then(() => {
          // 观察：更改 props 对象值
          this.$message.success('提交成功!')
          this.handleClose()
          this.getData()
        })
        .finally(() => {
          this.submitLoading = false
          this.$emit('after-data', {})
        })
    },

    // 更新项目附件状态
    updateStatus() {
      // 判断附件状态
      const listObj = this.attachs.reduce((prev, curr) => {
        const tag = curr.attachment_type
        if (!prev[tag]) prev[tag] = []
        prev[tag].push(curr)
        return prev
      }, {})
      const isAllUpload = this.uploadTags.every(tag => {
        const isOnline = tag.slot === contractSlot && this.isOnlineSign === 1
        if (isOnline) {
          return this.customerSignApproval === 1
        }
        if (!tag.required) return true
        const atts = listObj[tag.tag]
        return atts && atts.length > 0
      })
      const currentStatus = isAllUpload ? 1 : 0
      const attachStatus = +this.projectData.datum_status
      if (attachStatus === currentStatus) {
        return this.$emit('after-data', {})
      }

      // 更新状态
      this.$api
        .updateData({
          table: 'datum_one_county_industry',
          id: this.relatedId,
          data: {
            datum_status: currentStatus,
            is_corp_con: this.isCorp,
          },
        })
        .then(() => {
          // 观察：更改 props 对象值
          this.projectData.datum_status = currentStatus
        })
        .finally(() => {
          this.$emit('after-data', {})
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.attach-title {
  font-size: 1.1rem;
  font-weight: bold;
}
</style>
